package net.zjitc.dao.Impl;

import net.zjitc.dao.UserDao;
import net.zjitc.pojo.User;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by dell on 2017/11/18.
 */
public class UserDaoImpl implements UserDao {
    QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
    public List<User> findAllUser() {
        String sql="select * from user";
        try {
            List<User> list= (List<User>) runner.query(sql, new BeanListHandler(User.class));
            return  list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void userDelete(String uid) {
        String sql="delete from user where uid =?";
        try {
            runner.update(sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void userRegister(User user) {
        String sql="insert into user (username,password,name,email,phone,addr,state,code) values (?,?,?,?,?,?,?,?)";
        try {
            runner.update(sql,user.getUsername(),user.getPassword(),user.getName(),user.getEmail(),user.getPhone(),user.getAddr(),user.getState(),user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Boolean checkUsername(String username) {
        String sql = "select * from user where username=?";

        try {
            User user = (User) runner.query(sql, new BeanHandler(User.class), username);
            if (user != null) {//存在
                return true;//给前端响应 状态
            } else {//不存在
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User findByCode(String code) {
        String sql="select * from user where code =?";
        try {
            User user= (User) runner.query(sql,new BeanHandler(User.class),code);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void update(User user) {
        String sql="update user set username =?,password=?,name=?,email=?,phone=?,addr=?,state=?,code=? where uid=?";
        try {
            runner.update(sql,user.getUsername(),user.getPassword(),user.getName(),user.getEmail(),user.getPhone(),user.getAddr(),user.getState(),user.getCode(),user.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
